package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.entity.ApAuthor;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleContentService;
import com.heima.article.service.ApArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.service.ApAuthorService;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.constants.message.Article2EsConstants;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.common.util.JsonUtils;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.media.dtos.WmNewsResultDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.heima.common.constants.message.Article2EsConstants.ARTICLE_2_ES_TOPIC;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author HM
 * @since 2021-11-24
 */
@Slf4j
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    private ApArticleContentService apArticleContentService;
    @Autowired
    private ApAuthorService apAuthorService;
    @Autowired
    private ArticleFreemarkerService freemarkerService;
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    /**
     * 保存文章
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public Long saveArticle(WmNewsResultDTO dto) {
//        根据自媒体文章id 查询文章信息
        QueryWrapper<ApArticle> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ApArticle::getWmNewsId,dto.getId());
        ApArticle apArticle = getOne(queryWrapper);
        if(apArticle == null){
//         没有数据，新增
            apArticle = new ApArticle();
            apArticle.setWmNewsId(dto.getId());
//            根据自媒体文章作者查询文章作者id
            ApAuthor apAuthor = apAuthorService.findByWmUserId(dto.getWmUserId());
            if (apAuthor != null) {
                apArticle.setAuthorId(apAuthor.getId());
                apArticle.setAuthorName(apAuthor.getName());
            }
            apArticle.setLikes(0L);
            apArticle.setCollection(0L);
            apArticle.setComments(0L);
            apArticle.setViews(0L);
            apArticle.setIsComment(true);
            apArticle.setIsForward(true);
            apArticle.setIsDown(false);
            apArticle.setIsDelete(false);
            apArticle.setCreatedTime(new Date());
        }
        apArticle.setTitle(dto.getTitle());
        apArticle.setChannelId(dto.getChannelId());
        apArticle.setLayout(dto.getType());
        apArticle.setImages(dto.getImages());
        apArticle.setLabels(dto.getLabels());
        apArticle.setPublishTime(dto.getPublishTime()==null?new Date():dto.getPublishTime());
//        保存、修改ap_article
        boolean b = saveOrUpdate(apArticle);
        if(!b){
            log.error("保存aparticle失败！");
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
//        保存ap_article_content
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(dto.getContent());
        boolean b1 = apArticleContentService.saveOrUpdate(apArticleContent);
        if(!b1){
            log.error("保存aparticle失败！");
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }

//        生成静态页面
        freemarkerService.buildArticleToMinIO(apArticle,dto.getContent());
//        创建Es的索引库,msg可以传文章id，也可以传文章内容
        ArticleDto articleDto = BeanHelper.copyProperties(apArticle, ArticleDto.class);
        articleDto.setContent(dto.getContent());
        kafkaTemplate.send(ARTICLE_2_ES_TOPIC, JsonUtils.toString(articleDto));
        return apArticle.getId();
    }

    /**
     * 文章首页
     * @param dto
     * @return
     */
    @Override
    public List<ArticleDto> load(ArticleHomeDto dto,int type) {

//        设置分页
        IPage<ApArticle> iPage = new Page<>(1,dto.getSize());
//        设置条件
        QueryWrapper<ApArticle> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().
                eq(ApArticle::getIsDown,false).
                eq(ApArticle::getIsDelete,false);
        if(dto.getChannelId() != null && dto.getChannelId() !=0){
            queryWrapper.lambda().eq(ApArticle::getChannelId,dto.getChannelId());
        }
//        下拉操作
        if (type==1 && dto.getMaxTime() != null){
            queryWrapper.lambda().gt(ApArticle::getPublishTime,dto.getMaxTime());
        }
//        上拉操作
        if(type==2 && dto.getMinTime() != null){
            queryWrapper.lambda().lt(ApArticle::getPublishTime,dto.getMinTime());
        }
//        排序,根据发布时间倒序
        queryWrapper.lambda().orderByDesc(ApArticle::getPublishTime);
//        分页查询
        IPage<ApArticle> apArticleIPage = page(iPage, queryWrapper);
        if(apArticleIPage == null || CollectionUtils.isEmpty(apArticleIPage.getRecords())){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        return BeanHelper.copyWithCollection(apArticleIPage.getRecords(),ArticleDto.class);
    }

    /**
     * 消息内容，articleId，enable  0-上架  1-下架
     * @param map
     */
    @Override
    public void downOrUp(Map<String, Long> map) {


        ApArticle apArticle = new ApArticle();
        apArticle.setId(map.get("articleId"));
        apArticle.setIsDown(map.get("enable")==1);
        updateById(apArticle);
    }
    /**
     * 分页查询 文章数据
     * @param page
     * @param size
     * @return
     */
    @Override
    public List<ArticleDto> findByPage(Integer page, Integer size) {

//        设置分页
        IPage<ApArticle> iPage = new Page<>(page,size);

        List<ArticleDto> list = getBaseMapper().selectArticleAndContent(iPage);

        return list;
    }
}
